#pragma once
#include <iostream>
#include <unistd.h>
#include"log.hpp"
#include"dict.hpp"
using namespace std;

class task
{
public:
    void serverce(int socketfd, const string &userIp, uint16_t userPort)
    {
        char getMsg[1024];
        //while (true)//将长服务改为短服务
        //{
            // 获取数据
            int n = read(socketfd, getMsg, sizeof(getMsg) - 1);
            if (n == -1)
            {
                log(WORNING, "read fail");
                return;
                //break;
            }
            else if (n == 0)
            {
                cout << "[" << userIp << ":" << userPort << "] quit" << endl;
                return;
                //break;
            }
            getMsg[n] = '\0';

            // cout<<getMsg<<endl;

            // 制作返回客户端的数据并返回
            string sendMsg = "[" + userIp + ":" + to_string(userPort) + "] " + getMsg;
            write(socketfd, sendMsg.c_str(), sendMsg.size());
            close(socketfd);
        //}
    }

    void translation(int socketfd, const string &userIp, uint16_t userPort)
    {
        char getMsg[1024];
        //while (true)//将长服务改为短服务
        
            // 获取数据
            int n = read(socketfd, getMsg, sizeof(getMsg) - 1);
            if (n == -1)
            {
                log(WORNING, "read fail");
                return;
                //break;
            }
            else if (n == 0)
            {
                cout << "[" << userIp << ":" << userPort << "] quit" << endl;
                return;
                //break;
            }
            getMsg[n] = '\0';

            string sendInfo;
            for(auto word:dict::getdict()->_dict)
            {
                if(word.first==getMsg)
                    sendInfo+=word.second;
            }
            if(sendInfo.size()==0)
                sendInfo="unkonw";


            // cout<<getMsg<<endl;

            // 制作返回客户端的数据并返回
            string sendMsg = "[" + userIp + ":" + to_string(userPort) + "] " + sendInfo;
            write(socketfd, sendMsg.c_str(), sendMsg.size());
            close(socketfd);
    }

    task(int socketfd, const string &userIp, uint16_t userPort)
    :_socketfd(socketfd),_userIp(userIp),_userPort(userPort)
    {}

    task()=default;

    void operator()()
    {
        //serverce(_socketfd,_userIp,_userPort);
        translation(_socketfd,_userIp,_userPort);
    }

private:
    int _socketfd;
    string _userIp;
    uint16_t _userPort;
};